home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 8303 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.1 KB

  1. Path: gollum.kingston.net!usenet
  2. From: girard@haventree.com (Eugene Girard)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Why Do I Use An Ampersand in Member Class Parameters?
  5. Date: Fri, 16 Feb 1996 17:33:25 GMT
  6. Organization: HavenTree Software, Limited
  7. Message-ID: <4g2im4$sv3@gollum.kingston.net>
  8. References: <4emnv2$n5o@alcor.usc.edu>
  9. NNTP-Posting-Host: buddy.haventree.com
  10. X-Newsreader: Forte Free Agent v0.55
  11.  
  12. wawda@alcor.usc.edu (Abu Wawda) wrote:
  13.  
  14. >I mean, I would understand if I parameter were a pointer to a Simple
  15. >class, but that is not the case, since I am not doing:
  16.  
  17. >int Simple::operator += (const Simple ¶meter)
  18. >{
  19. >  data += parameter->data;
  20. >}
  21.  
  22. >Then why is there an amersand? I would appreciate any
  23. >suggestions. Thank you!
  24.  
  25. Two possible answere (since I'm not sure which question you are
  26. asking...)
  27. Q1) Why do you use an ampersand in an assignment operator?
  28. A1) Because if you don't then a copy constructor will be called to 
  29. pass the parameter.  IE:
  30.  
  31.      Simple &Simple::operator+=( const Simple param)
  32.      {
  33.        data += param.data;
  34.        return (*this);
  35.      }
  36. would cause Simple's copy constructor to be called whenever you
  37. write something like:
  38.      Simple x, y;
  39.      x += y;
  40. Which would obviously be quite bad for complex classes.
  41.  
  42. Q2) If foo( B &x) actually takes a pointer to x, then why can you
  43. refer to x.data instead of x->data inside of foo?
  44. A2) This is because references are special extensions to the 
  45. language.  If you want to, you can think of a reference parameter
  46. as adding a & before every variable passed in to the function, and
  47. adding an * before every reference to the variable inside of the 
  48. function.  (Of course, this is done invisibly to the programmer.)
  49. Thus,
  50.      void Foo( X &d)
  51.      {  d.data += 10;}
  52.      ...
  53.      Foo( q);
  54. is effectively translated to
  55.      void Foo( X *d)
  56.      { (*d).data += 10;}
  57.      ...
  58.      Foo( &(q));
  59. when the compiler operates on it.
  60.  
  61.   
  62. --
  63. Eugene Girard, Programmer, HavenTree Software Limited
  64. HavenTree makes EasyFlow (Windows, DOS, MAC) and Nodemap (Windows, DOS)
  65. For more information, check out http://www.haventree.com
  66.  
  67.